package cool.taomu.toolkit.service.centre.kademlia.utils

import com.google.gson.Gson
import cool.taomu.toolkit.service.kademlia.entity.KPeerNode
import cool.taomu.toolkit.service.kademlia.service.ICheckPeer
import cool.taomu.toolkit.service.kademlia.service.KRoutingTable
import cool.taomu.toolkit.utils.FileTools
import java.io.File
import org.apache.commons.io.FileUtils
import org.apache.oro.text.perl.Perl5Util
import org.slf4j.LoggerFactory

class KRoutingTableUtils {
    val static LOG = LoggerFactory.getLogger(KRoutingTableUtils);

    /**
     * 加载torrent目录下已经存在的配置节点到KRoutingTable中
     */
    def static KRoutingTable loadConfig(KRoutingTable rtable, ICheckPeer checkpeer) {
        if (checkpeer !== null) {
            FileTools.scannerFile("./torrent", [
                LOG.info("扫描到文件:{}", it.name)
                var p5 = new Perl5Util()
                if (p5.match("/^([a-zA-Z0-9.-]+)\\.([0-9]+)\\.local\\.torrent$/", it.name)) {
                    LOG.info("匹配到文件:{}", it.name)
                    var jsonFilename = it.absolutePath.replace(".torrent", ".json")
                    var jsonStr = FileUtils.readFileToString(new File(jsonFilename), "UTF-8")
                    LOG.info("将读取到的配置添加到k桶")
                    rtable.addPeerNode(new Gson().fromJson(jsonStr, KPeerNode), checkpeer)
                    LOG.info("添加完成")
                }
            ])
        }else{
          LOG.info("checkpeer为null，不进行节点配置添加")  
        }
        LOG.info("返回最終的路由表");
        return rtable;
    }
}
